package com.yf.stat.modules.exam.service.impl;

import cn.hutool.http.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.documents4j.api.DocumentType;
//import com.documents4j.api.IConverter;
//import com.documents4j.job.LocalConverter;
import com.yf.ability.upload.providers.local.config.LocalConfig;
import com.yf.ability.upload.providers.local.service.LocalUpService;
import com.yf.ability.upload.providers.local.utils.OssUtils;
import com.yf.base.api.api.dto.PagingReqDTO;

import com.yf.exam.modules.exam.dto.ExamDTO;
import com.yf.exam.modules.exam.entity.Exam;
import com.yf.exam.modules.exam.service.ExamDepartService;
import com.yf.exam.modules.exam.service.ExamService;
import com.yf.exam.modules.paper.dto.ext.PaperGroupExtDTO;
import com.yf.exam.modules.paper.dto.ext.PaperQuAnswerExtDTO;
import com.yf.exam.modules.paper.dto.ext.PaperQuDetailDTO;
import com.yf.exam.modules.paper.dto.response.ExamResultRespDTO;
import com.yf.exam.modules.paper.entity.Paper;
import com.yf.exam.modules.paper.service.PaperService;
import com.yf.stat.modules.exam.dto.*;
import com.yf.stat.modules.exam.dto.request.StatAnalyseReqDTO;
import com.yf.stat.modules.exam.dto.request.StatExamReqDTO;
import com.yf.stat.modules.exam.dto.request.StatQuReqDTO;
import com.yf.stat.modules.exam.mapper.StatExamMapper;
import com.yf.stat.modules.exam.service.StatExamService;
import com.yf.system.modules.depart.service.SysDepartService;
import com.yf.system.modules.dict.service.SysDicValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

//import java.io.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
* <p>
* 考试总体统计业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2020-09-11 11:10
*/
@Service
public class StatExamServiceImpl implements StatExamService {

    @Autowired
    private ExamService examService;

    @Autowired
    private SysDepartService sysDepartService;

    @Autowired
    private ExamDepartService examDepartService;

    @Autowired
    private StatExamMapper statExamMapper;

    @Autowired
    private PaperService paperService;

    @Autowired
    private LocalUpService upService;

    @Autowired
    private SysDicValueService sysDicValueService;



    @Override
    public StatExamTotalDTO findOverview(String examId) {
        ExamDTO exam = examService.findById(examId);
        return statExamMapper.findOverview(examId, exam.getOpenType());
    }

    @Override
    public IPage<StatExamUserDTO> userPaging(PagingReqDTO<StatExamReqDTO> reqDTO) {


        // 考试ID
        String examId = reqDTO.getParams().getExamId();

        // 开放类型
        Exam exam = examService.getById(examId);

        // 查找人员列表
        IPage<StatExamUserDTO> pageData = statExamMapper.userPaging(reqDTO.toPage(), reqDTO.getParams(), exam.getOpenType());
        return pageData;
     }



    @Override
    public List<StatExamTotalDTO> listStatTree(String examId) {

        Exam exam = examService.getById(examId);
        
        // 查找统计数据
        List<StatExamTotalDTO> dataList = statExamMapper.statByDepart(examId, exam.getOpenType());

        return dataList;
    }



    @Override
    public List<StatExamTotalDTO> listExpandTree(String examId) {

        List<StatExamTotalDTO> dataList = this.listStatTree(examId);
        return dataList;
    }

    @Override
    public IPage<StatErrorQuDTO> errorQuPaging(PagingReqDTO<StatQuReqDTO> reqDTO) {
        return statExamMapper.errorQuPaging(reqDTO.toPage(), reqDTO.getParams());
    }

    /**
     * 获取用户全部的考试信息
     * @param statStudentExamAnalyseDTO
     */
    @Override
    public StatAnalyseReqDTO studentAI(StatStudentExamAnalyseDTO statStudentExamAnalyseDTO) {
        StatAnalyseReqDTO statAnalyseReqDTO=new StatAnalyseReqDTO();
        statAnalyseReqDTO.setExamId(statStudentExamAnalyseDTO.getExamId());
        statAnalyseReqDTO.setRetType("student");
        String paperId =statStudentExamAnalyseDTO.getPaperId();
        if (statStudentExamAnalyseDTO.getPaperId()==null || statStudentExamAnalyseDTO.getPaperId().equals("")) {
            //根据情况获取用户考试信息
            paperId = statExamMapper.studentAI(statStudentExamAnalyseDTO);
        }
        ExamResultRespDTO examResultRespDTO = paperService.paperResult(paperId);
//        JSONObject jsonObject2 = getJsonObjectJson(statStudentExamAnalyseDTO.getExamId(),"Exam",examResultRespDTO.getTitle(),examResultRespDTO);
        statAnalyseReqDTO.setPaperID(paperId);
        if (examResultRespDTO.getExamText()==null || examResultRespDTO.getExamText().equals("")) {
            JSONObject jsonObject1 = getJsonObjectJson(statStudentExamAnalyseDTO.getExamId(),"Exam",examResultRespDTO.getTitle(),examResultRespDTO);
            //发送请求-返回存储的结果值
            String text = postText(jsonObject1,"student");
            //存储到数据库中，examid,text,userid
            statAnalyseReqDTO.setExamText(text);
            storagePdf(paperId, text);
            return statAnalyseReqDTO;
        }else {
            statAnalyseReqDTO.setExamText(examResultRespDTO.getExamText());
            return statAnalyseReqDTO;
        }
    }

    /**
     * 班级成绩分析
     * @param statStudentExamAnalyseDTO
     * @return
     */
    @Override
    public StatAnalyseReqDTO classAI(StatStudentExamAnalyseDTO statStudentExamAnalyseDTO) {
        StatAnalyseReqDTO statAnalyseReqDTO=new StatAnalyseReqDTO();
        JSONObject jsonObject=new JSONObject();
        String paperId=statStudentExamAnalyseDTO.getPaperId();
        String examName=null;
        statAnalyseReqDTO.setExamId(statStudentExamAnalyseDTO.getExamId());
        StatClassTextInfoDTO byText = statExamMapper.findByText(statStudentExamAnalyseDTO);
        if (byText != null) {
            if (byText.getContext() != null) {
                statAnalyseReqDTO.setExamText(byText.getContext());
                return statAnalyseReqDTO;
            }
        }
        //检索班级人员
        List<StatUserListDTO> userByDep = statExamMapper.findUserByDep(statStudentExamAnalyseDTO);
        List<JSONObject> studentList=new ArrayList<>();
        if (userByDep.size()>0){
            for (StatUserListDTO demo:userByDep) {
                StatStudentExamAnalyseDTO userDep = new StatStudentExamAnalyseDTO();
                userDep.setExamId(statStudentExamAnalyseDTO.getExamId());
                userDep.setUserId(demo.getUserId());
                paperId = statExamMapper.studentAI(userDep);
                if (paperId!=null){
                    //获取数据
                    ExamResultRespDTO examResultRespDTO = paperService.paperResult(paperId);
                    if (examName==null)
                        examName=examResultRespDTO.getTitle();
                    //封装1人Id
                    JSONObject aClass = getJsonObjectJson(statStudentExamAnalyseDTO.getExamId(), "Name",demo.getUserName(), examResultRespDTO);
                    studentList.add(aClass);
                }
            }
        }

        jsonObject.put("Exam",examName);
        jsonObject.put("Students",studentList);
        //获取统计
        String s = postText(jsonObject, "class");
        statStudentExamAnalyseDTO.setId(String.valueOf(UUID.randomUUID()));
        statStudentExamAnalyseDTO.setTextContext(s);
        if (byText==null) {
            statExamMapper.saveInfoByClass(statStudentExamAnalyseDTO);
        }else {
            byText.setContext(s);
            statExamMapper.updateClassInfo(byText);
        }

        statAnalyseReqDTO.setExamText(s);
        return statAnalyseReqDTO;
    }



    public JSONObject getJsonObjectJson(String examId, String type,String typeValue,ExamResultRespDTO examResultRespDTO){
            //封装map集合
            StringBuilder str = new StringBuilder();
            List<PaperGroupExtDTO> groupList = examResultRespDTO.getGroupList();
            List<StatQuestionDTO> questList = new ArrayList<>();
            Integer index=0;
            for (int i = 0; i < groupList.size(); i++) {
                PaperGroupExtDTO paperGroupExtDTO = groupList.get(i);
                List<PaperQuDetailDTO> quList = paperGroupExtDTO.getQuList();
                for (PaperQuDetailDTO quDetailDTO : quList) {
                    str.append(quDetailDTO.getQuId());
                    str.append(",");
                    StatQuestionDTO statQuestionDTO = new StatQuestionDTO();
                    statQuestionDTO.setQuId(quDetailDTO.getQuId());
                    statQuestionDTO.setYear("");
                    statQuestionDTO.setCategory("");
                    statQuestionDTO.setQuestion(quDetailDTO.getContent());
                    if (quDetailDTO.getQuType().equals("1")) {
//                    单选题
                        statQuestionDTO.setQuestionType("choice");
                    } else if (quDetailDTO.getQuType().equals("5")) {
//                    填空题
                        statQuestionDTO.setQuestionType("filling");
                    } else if (quDetailDTO.getQuType().equals("3")) {
//                    true-or-false 判断题
                        statQuestionDTO.setQuestionType("true-or-false");
                        List<String> collect = quDetailDTO.getAnswerList().stream()
                                .filter(item -> item.getIsRight() == true)
                                .map(item -> item.getContent())
                                .collect(Collectors.toList());
                        List<String> collect1 = quDetailDTO.getAnswerList().stream()
                                .filter(item -> item.getIsRight() == false)
                                .map(item -> item.getContent())
                                .collect(Collectors.toList());
                        statQuestionDTO.setAnswer(collect.get(0)!=null ? collect.get(0) : "无");
                        if (quDetailDTO.getIsRight()){
                            statQuestionDTO.setStudent_answer(collect.get(0));
                        }else {
                            statQuestionDTO.setStudent_answer(collect1.get(0));
                        }
                    } else if (quDetailDTO.getQuType().equals("4")) {
//                    short-answer-question 简答题
                        statQuestionDTO.setQuestionType("short-answer-question");
//                        List<String> answerList = new ArrayList<>();
//                        answerList.add(quDetailDTO.getAnalysis());
                        statQuestionDTO.setAnswer(quDetailDTO.getAnalysis()!=null ? quDetailDTO.getAnalysis() : "无");
                        if (!quDetailDTO.getAnswerList().isEmpty())
                            statQuestionDTO.setStudent_answer(quDetailDTO.getAnswerList().get(0).getAnswer() != null ? quDetailDTO.getAnswerList().get(0).getAnswer() : "无");
                        else
                            statQuestionDTO.setStudent_answer("无");
                    } else if (quDetailDTO.getQuType().equals("2")) {
                        statQuestionDTO.setQuestionType("choicemore");
                    }
                    List<PaperQuAnswerExtDTO> answerList = quDetailDTO.getAnswerList();
                    if (answerList.size() != 0) {
                        //查找答案
                        for (PaperQuAnswerExtDTO quAnswerExtDTO : answerList) {
                            /* 非简答题的写法 */
                            if (statQuestionDTO.getQuestionType().equals("choice")) {
                                if (quAnswerExtDTO.getChecked()) {
                                    statQuestionDTO.setStudent_answer(quAnswerExtDTO.getAbc()!=null ? quAnswerExtDTO.getAbc() : "无");
                                }
                                if (quAnswerExtDTO.getIsRight()) {
                                    statQuestionDTO.setAnswer(quAnswerExtDTO.getContent()!=null ? quAnswerExtDTO.getContent() : "无");
                                }
                            } else if (statQuestionDTO.getQuestionType().equals("filling")) {
                                statQuestionDTO.setAnswer(quAnswerExtDTO.getContent()!=null ? quAnswerExtDTO.getContent() : "无");
                                statQuestionDTO.setStudent_answer(quAnswerExtDTO.getAnswer()!=null ? quAnswerExtDTO.getAnswer() : "无");
                            }
                        }
                    }
                    statQuestionDTO.setAnalysis("");
                    statQuestionDTO.setIndex(++index);
                    statQuestionDTO.setScore(quDetailDTO.getScore());
                    statQuestionDTO.setStudent_score(quDetailDTO.getActualScore());
                    statQuestionDTO.setSyllabus("");
                    questList.add(statQuestionDTO);
                }
            }
//            更新知识点
            updateKnowledge(examId, str, questList);
            //封装json examResultRespDTO.getTitle()
            JSONObject jsonObject1 = getJsonObject(typeValue, questList, type);
            return jsonObject1;
    }
    /**
     * 获取知识点
     * @param examId
     * @param str
     * @param questList
     */
    private void updateKnowledge(String examId,StringBuilder str,List<StatQuestionDTO> questList){
        Map<String, String> aiExamConf = sysDicValueService.findDictMap("aiExam_conf");
        //获取知识点
        String host = aiExamConf.get("pathUrl");
        String path = aiExamConf.get("apiPath1");
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("exam_id",examId);
        jsonObject.put("question_list",str.substring(0,str.length()-1));
        String response = HttpUtil.createPost(host+path)
                .header("Content-Type","application/json")
                .header("Connection","keep-alive")
                .header("Accept","text/html;charset=UTF-8;")
                .timeout(8000)
                .body(jsonObject.toJSONString())
                .execute()
                .body();
        JSONObject resultJson=JSONObject.parseObject(response);
        if (resultJson.containsKey("data")){
            //存在表明可以获取
            JSONArray list = resultJson.getJSONArray("data");
            for (int i=0;i<list.size();i++){
                JSONObject jsonObject1=(JSONObject) list.get(i);
                String quId=jsonObject1.getString("question_id");
                for (StatQuestionDTO statQuestionDTO:questList){
                    if (statQuestionDTO.getQuId().equals(quId)){
                        statQuestionDTO.setKnowledge_point(jsonObject1.getString("knowledge"));
                    }
                }
            }
        }else {
            for (StatQuestionDTO statQuestionDTO:questList){
                statQuestionDTO.setKnowledge_point("");
            }
        }

    }

    /**
     * 保存生成的试卷分析
     * @param paperId
     * @param text
     */
    private void storagePdf(String paperId,String text) {
        Paper paper=new Paper();
        paper.setId(paperId);
        paper.setExamText(text);
        paperService.saveById(paper);
    }

    /**
     * 返回解析的信息
     * @param jsonObject
     * @return
     */
    private String postText(JSONObject jsonObject,String type) {
        Map<String, String> aiExamConf = sysDicValueService.findDictMap("aiExam_conf");
        //获取知识点
        String host = aiExamConf.get("pathUrl");
        String path =null;
        String fileName="";
        if (type.equals("student")) {
            path = aiExamConf.get("apiPath4");
            fileName="Student";
        }else {
            path = aiExamConf.get("apiPath5");
            fileName="Class";
        }
        LocalConfig config = upService.getConfig();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String dates=simpleDateFormat.format(new Date());
        //生成文件地址
        String paths=dates.substring(0,4)+"/"+dates.substring(5,7)+"/"+dates.substring(8,10);
        //生成文件总地址
        String dir=config.getLocalDir()+paths;
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        HttpRequest request = HttpRequest.get(host+path);
        Map<String,String> header=new HashMap<>();
        header.put("Content-Type","application/json");
        header.put("Connection","keep-alive");
        header.put("Accept","text/html;charset=UTF-8;");
        header.put("Access-Control-Allow-Origin", "*");
        request.addHeaders(header);
        request.body(jsonObject.toJSONString());
        request.timeout(800000);
        // 发送请求并获取HttpResponse对象
        HttpResponse response = request.execute();
        String saveFilePath="";
        String fileId=String.valueOf(UUID.randomUUID());
        // 检查响应状态码
        if (response.getStatus()==200) {
            // 要保存的文件路径
            saveFilePath = dir+"/"+fileName+"-"+fileId+".docx";
            try  {
                //接收字节流
                byte[] inputStream = response.bodyBytes();
//                // 创建文件夹
                OssUtils.checkDir(saveFilePath);
                // 上传文件
                FileCopyUtils.copy(inputStream, new FileOutputStream(saveFilePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return paths + "/"+fileName+"-" + fileId + ".docx";
        } else {
            return null;
        }
    }

    /**
     * word转为pdf
     * @param saveFilePath
     */
//    private String downloadFile(String saveFilePath,String dir,String openFile){
//
//        try  {
//            System.out.println("取地址"+saveFilePath);
//            System.out.println("存地址"+dir+openFile);
//            InputStream docxInputStream = new FileInputStream(saveFilePath);
//            OutputStream outputStream = new FileOutputStream(dir+openFile);
//            XWPFDocument document = new XWPFDocument(docxInputStream);
//            PdfOptions options = PdfOptions.create();
//            // Convert .docx file to .pdf file
//            PdfConverter.getInstance().convert(document, outputStream, options);
////            IConverter converter = LocalConverter.builder().build();
////            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
//            outputStream.close();
//            return openFile;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//
//    }

    /**
     * 获取知识点
     */
    private JSONObject getJsonObject(String ExamTitle,List<StatQuestionDTO> questList,String Type){
        JSONObject jsonObject=new JSONObject();
        List<Map<String,Object>> jsonList=new ArrayList<>();
        for (StatQuestionDTO statQuestionDTO:questList){
            Map<String ,Object> map=new HashMap<>();
            map.put("year",statQuestionDTO.getYear());
            map.put("category",statQuestionDTO.getCategory());
            map.put("question",statQuestionDTO.getQuestion());
            map.put("answer",statQuestionDTO.getAnswer());
            map.put("analysis",statQuestionDTO.getAnalysis());
            map.put("index",statQuestionDTO.getIndex());
            map.put("score",statQuestionDTO.getScore());
            map.put("student_answer",statQuestionDTO.getStudent_answer());
            map.put("student_score",statQuestionDTO.getStudent_score());
            map.put("knowledge_point",statQuestionDTO.getKnowledge_point());
            map.put("syllabus",statQuestionDTO.getSyllabus());
            map.put("question_type",statQuestionDTO.getQuestionType());
            jsonList.add(map);
        }
        jsonObject.put(Type,ExamTitle);
        jsonObject.put("Questions",jsonList);
        return jsonObject;
    }

}
